package com.example.administrator.officeplatform.Activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Layout;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baoyz.actionsheet.ActionSheet;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.adapter.PhotoAdapter;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.base.BaseSpinnerAdapter;
import com.example.administrator.officeplatform.bean.Constant;
import com.example.administrator.officeplatform.bean.CostInfo;
import com.example.administrator.officeplatform.bean.Fileinfo;
import com.example.administrator.officeplatform.bean.LoanInfo;
import com.example.administrator.officeplatform.bean.ReimbursementVoInfo;
import com.example.administrator.officeplatform.bean.SpinnerInfo;
import com.example.administrator.officeplatform.bean.TimeInfo;
import com.example.administrator.officeplatform.kj.AuditorActivity;
import com.example.administrator.officeplatform.kj.BMSearchActivity;
import com.example.administrator.officeplatform.kj.ImageScaleUtil;
import com.example.administrator.officeplatform.kj.IpUtil;
import com.example.administrator.officeplatform.kj.LoanActivity;
import com.example.administrator.officeplatform.kj.PersonActivity;
import com.example.administrator.officeplatform.kj.TimeActivity;
import com.example.administrator.officeplatform.kj.TimeSearch;
import com.example.administrator.officeplatform.kj.WorkflowConfigActivity;
import com.example.administrator.officeplatform.utils.DateUtil;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.example.administrator.officeplatform.utils.UILImageLoader;
import com.example.administrator.officeplatform.utils.UpLoadPhotoUtil;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StorageUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

import static cn.finalteam.toolsfinal.DateUtils.date;
import static com.example.administrator.officeplatform.R.id.layout_travelp;

public class CostActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar toolbar;
    private LinearLayout layout,layout_bc,layout_tj;
    private int index;
    private TextView tv_upload,tv_add,tv_selecttime,tv_bm,tv_dh,tv_rq,tv_hjje,tv_jk,tv_shr,tv_lc;
    private DatePickerDialog dpd;
    private Context mContext;
    private Spinner msp_is;
    private List<Integer> numlist;
    private BigDecimal allmoney ;
    private BigDecimal jk ;
    private ArrayList listtime = new ArrayList();
    private PhotoAdapter photoAdapter;
    private List<PhotoInfo> mPhotoList;
    private int REQUEST_CODE_CAMERA=1;
    private final int REQUEST_CODE_GALLERY = 1001;
    private Integer startNum;
    private ProgressDialog mProgressDialog;
    private RecyclerView recyclerView;
    private List<CostInfo> mcostList;
    private Button btn_jingjia,btn_bc;
    private ReimbursementVoInfo travelMaininfo;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg");
    private List<Fileinfo> ls_file;
    private OkHttpClient mOkHttpClient= new OkHttpClient();
    private String id,nextAuditorId,departName,departId;

    private int mYear, mMonth, mDay;
    final int DATE_DIALOG = 1;

    private String seleteIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_cost);

    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        allmoney = new BigDecimal(0);
        jk = new BigDecimal(0);
        index = 0;
        layout = (LinearLayout) findViewById(R.id.layout_cost);
        layout_bc = (LinearLayout) findViewById(R.id.layout_bc);
        layout_tj = (LinearLayout) findViewById(R.id.layout_tj);
        layout_tj.setVisibility(View.GONE);
        btn_bc = (Button) findViewById(R.id.btn_bc);
        tv_add = (TextView) findViewById(R.id.tv_add);
        tv_selecttime = (TextView) findViewById(R.id.tv_rq);
        msp_is = ((Spinner)findViewById(R.id.sp_is1));

        tv_bm = (TextView) findViewById(R.id.tv_bm);
        tv_dh = (TextView) findViewById(R.id.tv_dh);
        tv_rq = (TextView) findViewById(R.id.tv_rq);
        tv_hjje = (TextView) findViewById(R.id.tv_hjje);
        tv_jk = (TextView) findViewById(R.id.tv_jk);
        tv_shr = (TextView) findViewById(R.id.tv_shr);
        btn_jingjia = (Button)findViewById(R.id.btn_jingjia);
        tv_lc=(TextView)findViewById(R.id.tv_lc);


        Button button = (Button) findViewById(R.id.btn_jingjia);
        button.setOnClickListener(this);
        tv_upload = (TextView)findViewById(R.id.tv_upload);
        recyclerView=(RecyclerView)findViewById(R.id.rv_photo);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));// 布局管理器。
        recyclerView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        recyclerView.setItemAnimator(new DefaultItemAnimator());//
        initConfig();
        init();

    }

    @Override
    protected void initData() {
        toolbar.setTitle("成本费用报销单");
        mContext = this;
        numlist = new ArrayList<>();
        mcostList = new ArrayList<>();
        travelMaininfo=new ReimbursementVoInfo();
        ls_file = new ArrayList<>();

        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        departName=sharedPreferences.getString("departName","");
        tv_bm.setText(departName);
        departId = sharedPreferences.getString("orgId","");
        travelMaininfo.setDepartmentId(departId);
        travelMaininfo.setDepartmentName(departName);

        Time t = new Time();
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int date = t.monthDay;
        tv_selecttime.setText(year + "-" + (month +1 ) + "-"
                + date);

        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);


        ArrayList ls1 = new ArrayList();
        ls1.add(new SpinnerInfo("1", "否"));
        ls1.add(new SpinnerInfo("2", "是"));
        BaseSpinnerAdapter Adapter1 = new BaseSpinnerAdapter(layout.getContext(), ls1);
        msp_is.setAdapter(Adapter1);
        addView();
        mPhotoList = new ArrayList<>();
        final PhotoInfo photoInfo = new PhotoInfo();
        mPhotoList.add(photoInfo);
        setRecyclerView();
        String orgId=MyApplication.getOrgId();
        if(null==orgId||orgId.length()==0){
            Toast.makeText(this, "未获取到部门Id，无法生成单号", Toast.LENGTH_SHORT).show();
        }else{
            getNumber(orgId);

        }

    }

    @Override
    protected void initEvents() {
        tv_add.setOnClickListener(this);
//        tv_selecttime.setOnClickListener(this);
//        tv_bm.setOnClickListener(this);
        tv_upload.setOnClickListener(this);
        btn_jingjia.setOnClickListener(this);
        tv_shr.setOnClickListener(this);
        toolbar.setNavigationOnClickListener(this);
        tv_lc.setOnClickListener(this);
        btn_bc.setOnClickListener(this);


    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;

            for (int i = 0; i < layout.getChildCount(); i++) {
                View childAt = layout.getChildAt(i);
                String tag = childAt.getTag().toString();
                if (tag.equals(seleteIndex)) {
                    View child = childAt;
                    final TextView tv_time = (TextView)child.findViewById(R.id.tv_time);
                    tv_time.setText(mYear + "-" + (mMonth+1));
                    mcostList.get(i).setSettlementCycle(mYear + "-" + (mMonth+1)+"-"+mDay);
                    mcostList.get(i).setSettlementCycleName(mYear + "-" + (mMonth+1)+"-"+mDay);
                }
            }
        }
    };


    private void addView(){
        CostInfo costinfo = new CostInfo();
        costinfo.setDepartmentId(departId);
        costinfo.setDepartmentName(departName);
        mcostList.add(costinfo);
        LayoutInflater layoutInflater = getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.item_costview, null);
        view.setTag(index);
        layout.addView(view);
        numlist.add(index);
        final View child = layout.getChildAt(numlist.size()-1);
        Spinner sp_type = ((Spinner)child.findViewById(R.id.sp_type));
        Spinner sp_iscx = ((Spinner)child.findViewById(R.id.sp_iscx));

        final Spinner sp_is = ((Spinner)child.findViewById(R.id.sp_is));
        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("1", "成本"));
        ls.add(new SpinnerInfo("2", "费用"));
        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(layout.getContext(), ls);
        sp_type.setAdapter(Adapter);
        final LinearLayout layout_jk = (LinearLayout)child.findViewById(R.id.layout_jk);
        layout_jk.setVisibility(View.GONE);
        ArrayList ls1 = new ArrayList();
        ls1.add(new SpinnerInfo("1", "否"));
        ls1.add(new SpinnerInfo("2", "是"));
        BaseSpinnerAdapter Adapter1 = new BaseSpinnerAdapter(layout.getContext(), ls1);
        sp_is.setAdapter(Adapter1);
        sp_iscx.setAdapter(Adapter1);
        sp_is.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                SpinnerInfo spinnerInfo = (SpinnerInfo) sp_is.getSelectedItem();

                String type = spinnerInfo.getId();
                if (type.equals("2")) {
                    layout_jk.setVisibility(View.VISIBLE);

                } else if (type.equals("1")) {
                    layout_jk.setVisibility(View.GONE);
                    tv_jk.setText("0");

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

        final TextView tv_1 = (TextView)child.findViewById(R.id.tv_12);
        tv_1.setTag(index);
        tv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), PersonActivity.class);
                intent.putExtra("type", "0");
                intent.putExtra("index", tv_1.getTag().toString());
                startActivityForResult(intent, 1);
            }
        });
        final TextView tv_delete = (TextView)child.findViewById(R.id.tv_delete);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              int num =Integer.parseInt(child.getTag().toString()) ;
                int i = numlist.indexOf(num);
                mcostList.remove(i);
                numlist.remove(i);
                layout.removeView(child);
                getjk();
                getData();

            }
        });

        final TextView tv_time = (TextView)child.findViewById(R.id.tv_time);
        tv_time.setTag(index);
        tv_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                showDialog(DATE_DIALOG);
                seleteIndex= String.valueOf(tv_time.getTag());
            }
        });
        final TextView tv_jkd = (TextView)child.findViewById(R.id.tv_82);
        tv_jkd.setTag(index);
        tv_jkd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), LoanActivity.class);
                intent.putExtra("index", tv_jkd.getTag().toString());
                startActivityForResult(intent, 1);

            }
        });

        final TextView tv_depart = (TextView)child.findViewById(R.id.tv_depart);
        tv_depart.setText(departName);
        tv_depart.setTag(index);
        tv_depart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), BMSearchActivity.class);
                intent.putExtra("index", tv_depart.getTag().toString());
                intent.putExtra("type","1");
                startActivityForResult(intent, 1);

            }
        });

        EditText ed_xm = (EditText)child.findViewById(R.id.tv_22);
        EditText ed_bxbl = (EditText)child.findViewById(R.id.tv_52);
//        ed_bxbl.addTextChangedListener(new MoneyTextWatcher(ed_bxbl));
        EditText ed_je = (EditText)child.findViewById(R.id.tv_62);
        ed_je.setTag(index);
        ed_je.addTextChangedListener(new MoneyTextWatcher(ed_je));
        EditText ed_jk = (EditText)child.findViewById(R.id.tv_92);
        ed_jk.addTextChangedListener(new MoneyTextWatcher(ed_jk));
        ed_jk.setTag(index);

        index++;

    }



    private void getData(){
        allmoney = new BigDecimal(0);
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            EditText ed_je = (EditText)child.findViewById(R.id.tv_62);
            String jem = ed_je.getText().toString();
            if ("".equals(jem)||jem==null){

            }else {
                BigDecimal je = new BigDecimal(jem) ;
                allmoney = allmoney.add(je);
            }

        }
        tv_hjje.setText(String.valueOf(allmoney));
    }
    private void getjk(){
        jk = new BigDecimal(0);
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            EditText ed_jk = (EditText)child.findViewById(R.id.tv_92);
            String jem = ed_jk.getText().toString();
            if ("".equals(jem)||jem==null){

            }else {
                BigDecimal je = new BigDecimal(jem) ;
                jk = jk.add(je);
            }

        }
        tv_jk.setText(jk.toString());
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_add:
                addView();
                break;
            case R.id.tv_bm:
                Intent intent = new Intent();
                intent.putExtra("type", "0");
                intent.setClass(mContext, BMSearchActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.tv_upload:
                if(mPhotoList.size()-1==0){
                    Toast.makeText(this, "请先拍照", Toast.LENGTH_SHORT).show();
                }else{
                    startNum=0;
                    String file = mPhotoList.get(startNum).getPhotoPath();
                    uploadPhoto(file);
                }
                break;
            case R.id.btn_jingjia:
                if(isNull(tv_shr)){
                    Toast.makeText(mContext, "请选择审核人", Toast.LENGTH_SHORT).show();
                    return;
                }
                sendExpense();
                break;

            case R.id.tv_shr:
                Intent intent2 = new Intent();
                intent2.setClass(mContext, AuditorActivity.class);
                intent2.putExtra("index",id);
                startActivityForResult(intent2, 1);
                break;
            case R.id.tv_lc:
                Intent intent3 = new Intent();
                intent3.setClass(mContext, WorkflowConfigActivity.class);
                intent3.putExtra("type","expenseCost");
                startActivityForResult(intent3, 1);
                break;
            case R.id.btn_bc:
                setExpenseData();
                break;
            default:
                finish();
                break;
        }
    }




    /**
     * 刷新, 这种刷新方法，只有一个Activity实例。
     */
    public void refresh() {
        finish();
        Intent intent = new Intent();
        intent.setClass(mContext, CostActivity.class);
        startActivity(intent);
    }

    class Datelistener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            tv_selecttime.setText(year + "-" + (monthOfYear + 1) + "-"
                    + dayOfMonth);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 1) {
            String st = data.getExtras().getString("index");
            String person = data.getExtras().getString("person");
            String personid = data.getExtras().getString("personid");
            if(st.equals("shr")){
                tv_shr.setText(person);
                travelMaininfo.setNextAuditor(person);
                travelMaininfo.setNextAuditorId(personid);
            }else{
                for (int i = 0; i < layout.getChildCount(); i++) {
                    View childAt = layout.getChildAt(i);
                    String tag = childAt.getTag().toString();
                    if (tag.equals(st)) {
                        View child = childAt;
                        TextView tv_1 = (TextView) child.findViewById(R.id.tv_12);
                        tv_1.setText(person);
                        mcostList.get(i).setSupplierName(person);
                        mcostList.get(i).setSupplierId(personid);

                    }
            }

            }
        } else if (resultCode == 2) {
            String st = data.getExtras().getString("index");
            String departId = data.getExtras().getString("departId");
            tv_bm.setText(st);
            travelMaininfo.setDepartmentId(departId);
            travelMaininfo.setDepartmentName(st);
        } else if (resultCode == 3) {
            String st = data.getExtras().getString("index");
            String person = data.getExtras().getString("person");
            String id = data.getExtras().getString("id");

            for (int i = 0; i < layout.getChildCount(); i++) {
                View childAt = layout.getChildAt(i);
                String tag = childAt.getTag().toString();
                if (tag.equals(st)) {
                    View child = childAt;
                    TextView tv_1 = (TextView) child.findViewById(R.id.tv_time);
                    tv_1.setText(person);
                    mcostList.get(i).setSettlementCycleName(person);
                    mcostList.get(i).setSettlementCycle(id);

                }
            }

        } else if (resultCode == 4) {
            String st = data.getExtras().getString("index");
            final LoanInfo loanInfo = (LoanInfo) data.getExtras().get(
                    "loan");
            for (int i = 0; i < layout.getChildCount(); i++) {
                View childAt = layout.getChildAt(i);
                String tag = childAt.getTag().toString();
                if (tag.equals(st)) {
                    mcostList.get(i).setLoanId(loanInfo.getId());
                    View child = childAt;
                    TextView tv_1 = (TextView) child.findViewById(R.id.tv_82);
                    TextView tv_ye = (TextView) child.findViewById(R.id.tv_jkye);
                    final EditText tv_je = (EditText) child.findViewById(R.id.tv_62);
                    final EditText tv_jk = (EditText) child.findViewById(R.id.tv_92);
                    final Spinner sp_cx = (Spinner) child.findViewById(R.id.sp_iscx);
                    tv_1.setText("单号：" + loanInfo.getReimbursementCode() + "    金额：" + loanInfo.getLoanMoney());
                    tv_ye.setText(loanInfo.getLoanSurplusMoney().toString());
                    EditText ed_1 = (EditText) child.findViewById(R.id.tv_62);
                    BigDecimal num = new BigDecimal(0);
                    if (ed_1.getText().toString().equals("")){

                    }else {
                        num = new BigDecimal(ed_1.getText().toString());
                    }
                    Integer bjnum = num.compareTo(loanInfo.getLoanMoney());
                    if (bjnum==1||bjnum==0){
                        tv_jk.setText(loanInfo.getLoanMoney().toString());
                        sp_cx.setSelection(1);
                        sp_cx.setEnabled(false);
                        sp_cx.setClickable(false);
                    }else {
                        sp_cx.setSelection(0);
                        sp_cx.setEnabled(true);
                        sp_cx.setClickable(true);
                        tv_jk.setText(tv_je.getText().toString());
                        sp_cx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                            @Override
                            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                                       int arg2, long arg3) {
                                SpinnerInfo spinnerInfo = (SpinnerInfo) sp_cx.getSelectedItem();

                                String type = spinnerInfo.getId();
                                if (type.equals("1")) {
                                    tv_jk.setText(tv_je.getText().toString());

                                } else if (type.equals("2")) {
                                    tv_jk.setText(loanInfo.getLoanMoney().toString());

                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> arg0) {
                                // TODO Auto-generated method stub
                            }
                        });
                    }
                }
            }
        } else if (resultCode == 5){
            String st = data.getExtras().getString("index");
            String name = data.getExtras().getString("name");
            String departId =data.getExtras().getString("departId");
            for (int i = 0; i < layout.getChildCount(); i++) {
                View childAt = layout.getChildAt(i);
                String tag =  childAt.getTag().toString();
                if (tag.equals(st)){
                    View child = childAt;
                    TextView tv_1 = (TextView)child.findViewById(R.id.tv_depart);
                    tv_1.setText(name);
                    mcostList.get(i).setDepartmentName(name);
                    mcostList.get(i).setDepartmentId(departId);
                }
            }
        }
        else if (resultCode == 7){
            String processName = data.getExtras().getString("processName");
            String processId = data.getExtras().getString("processId");
            tv_lc.setText(processName);
            travelMaininfo.setWorkflowconfigId(processId);
        }else if (resultCode == 8){
            String name = data.getExtras().getString("name");
            nextAuditorId = data.getExtras().getString("id");
            tv_shr.setText(name);
        }
    }

    public class MoneyTextWatcher implements TextWatcher {
        private EditText editText;
        private int digits = 2;

        public MoneyTextWatcher(EditText et) {
            editText = et;
        }
        public MoneyTextWatcher setDigits(int d) {
            digits = d;
            return this;
        }


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //删除“.”后面超过2位后的数据
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > digits) {
                    s = s.toString().subSequence(0,
                            s.toString().indexOf(".") + digits+1);
                    editText.setText(s);
                    editText.setSelection(s.length()); //光标移到最后
                }
            }
            //如果"."在起始位置,则起始位置自动补0
            if (s.toString().trim().substring(0).equals(".")) {
                s = "0" + s;
                editText.setText(s);
                editText.setSelection(2);
            }

            //如果起始位置为0,且第二位跟的不是".",则无法后续输入
            if (s.toString().startsWith("0")
                    && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    editText.setText(s.subSequence(0, 1));
                    editText.setSelection(1);
                    return;
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

            switch (editText.getId()) {
                case R.id.tv_62:
                    getData();
                    String index = editText.getTag().toString();
//                    Toast.makeText(mContext, index, Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < layout.getChildCount(); i++) {
                        View childAt = layout.getChildAt(i);
                        String tag = childAt.getTag().toString();
                        if (tag.equals(index)) {
                            View child = childAt;
                            TextView tv_ye = (TextView) child.findViewById(R.id.tv_jkye);
                            final EditText tv_je = (EditText) child.findViewById(R.id.tv_62);
                            final EditText tv_jk = (EditText) child.findViewById(R.id.tv_92);
                            final Spinner sp_cx = (Spinner) child.findViewById(R.id.sp_iscx);
                            String locamoneystr = tv_ye.getText().toString();
                            BigDecimal locamoney = new BigDecimal(0);
                            if (!isNull(locamoneystr)||!"".equals(locamoneystr)){
                                 locamoney = new BigDecimal(locamoneystr);
                            }

                            EditText ed_1 = (EditText) child.findViewById(R.id.tv_62);
                            BigDecimal num = new BigDecimal(0);
                            if (ed_1.getText().toString().equals("")){

                            }else {
                                num = new BigDecimal(ed_1.getText().toString());
                            }
                            Integer bjnum = num.compareTo(locamoney);
                            if (bjnum==1||bjnum==0){
                                tv_jk.setText(locamoney.toString());
                                sp_cx.setSelection(1);
                                sp_cx.setEnabled(false);
                                sp_cx.setClickable(false);
                            }else {
                                sp_cx.setSelection(0);
                                sp_cx.setEnabled(true);
                                sp_cx.setClickable(true);
                                tv_jk.setText(tv_je.getText().toString());
                                final BigDecimal finalLocamoney = locamoney;
                                sp_cx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                                    @Override
                                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                                                               int arg2, long arg3) {
                                        SpinnerInfo spinnerInfo = (SpinnerInfo) sp_cx.getSelectedItem();

                                        String type = spinnerInfo.getId();
                                        if (type.equals("1")) {
                                            tv_jk.setText(tv_je.getText().toString());

                                        } else if (type.equals("2")) {
                                            tv_jk.setText(finalLocamoney.toString());

                                        }
                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> arg0) {
                                        // TODO Auto-generated method stub
                                    }
                                });
                            }
                        }
                    }
                    break;
                case R.id.tv_92:

                    getjk();
                    break;
            }
//            getData();
        }
    }

    private void getNumber(String departmentId){
        OkHttpClient mOkHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/createNumber/"+departmentId)
                .header("cookie", MyApplication.getMsession())
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //{"error":"您不属于事业部下,无法生成报销单号"}
                //{"number":"henfanachaojifana2017121900004"}
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(str.indexOf("error")>=0){
                            String Msg = JsonUtil.getMsg(str,"error");
                            Toast.makeText(mContext, Msg, Toast.LENGTH_SHORT).show();

                        }else if(str.indexOf("number")>=0){
                            String Msg = JsonUtil.getMsg(str,"number");
                            tv_dh.setText(Msg);
                            travelMaininfo.setReimbursementCode(Msg);
                        }else {
                            Toast.makeText(mContext, "未获取到单号", Toast.LENGTH_SHORT).show();
                        }

                    }
                });


            }
        });
    }

    /**
     *照相机框架配置
     *@author Wangzhiqiang
     *Created on 2017/12/18 14:14
     */
    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()
                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setFunctionConfig(functionConfig)
                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }
    /**
     *设置照片列表和点击事件
     *@author Wangzhiqiang
     *Created on 2017/12/18 15:28
     */
    private void setRecyclerView(){
        recyclerView.setAdapter(photoAdapter = new PhotoAdapter(this,mPhotoList));
        setRecyclerViewClick();
    }
    private void setRecyclerViewClick(){
        photoAdapter.setOnRecyclerViewListener(new PhotoAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(final int position) {
                if(position==mPhotoList.size()-1) {
//                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
//                        @Override
//                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
//                            if (resultList != null) {
//                                mPhotoList.add(0, resultList.get(0));
//                                setRecyclerView();
//                            }
//                        }
//
//                        @Override
//                        public void onHanlderFailure(int requestCode, String errorMsg) {
//                            Log.e("onHanlderFailure", "");
//                        }
//                    });
                    showActionSheet();

                }
            }

            @Override
            public boolean onItemLongClick(final int position) {
                if(position==mPhotoList.size()-1){
                }else{
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("确定要删除这张照片吗");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            mPhotoList.remove(position);
                            setRecyclerView();
                        }
                    });
                    builder.setNegativeButton("取消",null);
                    builder.show();

                }
                return false;
            }
        });
    }

    /**
     *拍照或从相册选择照片
     *@author Wangzhiqiang
     *Created on 2017/12/27 13:52
     */

    private void showActionSheet(){

        ActionSheet.createBuilder(mContext, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("打开相册", "拍照")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY,100, mOnHanlderResultCallback);
                                break;
                            case 1:
                                try {
                                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA,mOnHanlderResultCallback);
                                }catch (Exception e) {
                                    e.printStackTrace();
                                }

                                break;
                            default:
                                break;
                        }
                    }
                })
                .show();
    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {
                mPhotoList.addAll(0,resultList);
                setRecyclerView();

            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
        }
    };

     /**
    *上传图片
    *@author Wangzhiqiang
    *Created on 2017/12/18 15:31
    */
    private void uploadPhoto(String file){
        final String filename = DateUtil.getFileName();
        if(startNum==0){
            mProgressDialog = ProgressDialog.show(mContext, null, "正在上传中...");
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
//        builder.addFormDataPart("reimbursement_image", filename, RequestBody.create(MEDIA_TYPE_PNG, new File(file)));
        builder.addFormDataPart("reimbursement_image", filename, RequestBody.create(MEDIA_TYPE_PNG, ImageScaleUtil.getBitmapByte(ImageScaleUtil.scaleImage(file))));
        //构建请求体
        RequestBody requestBody = builder.build();

        //构建请求
        Request request = new Request.Builder()
                .url(IpUtil.getAddress())//地址
                .post(requestBody)//添加请求体
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                String str = response.body().string();
                //{"filename":"IMG201712211342_007877-1513834924333.jpg"}
                if (str.indexOf("filename") >= 0) {
                    Fileinfo fileinfo = new Fileinfo();
                    String  filename = JsonUtil.getMsg(str,"filename");
                    fileinfo.setFileUrl(filename);
                    ls_file.add(fileinfo);
                    if (startNum == mPhotoList.size() - 2) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Integer num = startNum+1;
                                Toast.makeText(mContext, "第"+num+"张图片上传成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                        return;
                    } else {
                        startNum++;
                        String file = mPhotoList.get(startNum).getPhotoPath();
                        uploadPhoto(file);
                    }
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "图片上传失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    ls_file.clear();
                    return;
                }
            }
        });

    }


    /**
     *上传数据
     *@author Wangzhiqiang
     *Created on 2017/12/20 14:21
     */
    private void setExpenseData(){
        if(isNull(tv_lc)){
            Toast.makeText(mContext, "请选取流程", Toast.LENGTH_SHORT).show();
            return;
        }

        if(isNull(tv_dh)){
            Toast.makeText(mContext, "请获取单号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(ls_file.size()==0){
            Toast.makeText(mContext, "请先上传附件", Toast.LENGTH_SHORT).show();
            return;
        }

        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            TextView tv_name = (TextView)child.findViewById(R.id.tv_12);
            TextView tv_depart = (TextView)child.findViewById(R.id.tv_depart);
            EditText et_xm = (EditText)child.findViewById(R.id.tv_22);
            TextView tv_time = (TextView)child.findViewById(R.id.tv_time);
            EditText et_bl = (EditText)child.findViewById(R.id.tv_52);
            EditText et_je = (EditText)child.findViewById(R.id.tv_62);
            TextView tv_jkd = (TextView)child.findViewById(R.id.tv_82);
            EditText et_jkmoney = (EditText)child.findViewById(R.id.tv_92);
            Spinner sp_type = (Spinner)child.findViewById(R.id.sp_type);
            Spinner sp_iscx = (Spinner)child.findViewById(R.id.sp_iscx);

            SpinnerInfo spinnerInfo=(SpinnerInfo)sp_type.getSelectedItem();
            int result = Integer.valueOf(spinnerInfo.getId());
            Spinner sp_is = (Spinner)child.findViewById(R.id.sp_is);
            SpinnerInfo spinnerInfo1=(SpinnerInfo)sp_is.getSelectedItem();
            int result1 = Integer.valueOf(spinnerInfo1.getId());
            if (result1==0){
                if (isNull(tv_jkd)){
                    Toast.makeText(mContext, "请选择借款单", Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    mcostList.get(i).setLoanNum(new BigDecimal(et_jkmoney.getText().toString()));
                }
            }
            if(isNull(tv_name)){
                Toast.makeText(mContext, "请选择供应商或员工", Toast.LENGTH_SHORT).show();
                    return;
            }
            if(isNull(et_xm)){
                Toast.makeText(mContext, "请填写费用项目", Toast.LENGTH_SHORT).show();
                return;
            }
            if(isNull(tv_time)){
                Toast.makeText(mContext, "请选择费用归属周期", Toast.LENGTH_SHORT).show();
                return;
            }

            if(isNull(et_je)){
                Toast.makeText(mContext, "请填写报销金额", Toast.LENGTH_SHORT).show();
                return;
            }

            else{
                mcostList.get(i).setCostProject(et_xm.getText().toString());
                mcostList.get(i).setCategoryName(String.valueOf(result));
                mcostList.get(i).setReimbursementProportion(et_bl.getText().toString());
                mcostList.get(i).setIsLoan(result1);
                mcostList.get(i).setMoney(new BigDecimal(et_je.getText().toString()));
//                mcostList.get(i).setSettlementCycle(tv_time.getText().toString());
//                mcostList.get(i).setSettlementCycleName(tv_time.getText().toString());
                SpinnerInfo info1=(SpinnerInfo)sp_type.getSelectedItem();
                mcostList.get(i).setCategory(info1.getId());
                mcostList.get(i).setCategoryName(info1.getText());
                SpinnerInfo info2=(SpinnerInfo)sp_is.getSelectedItem();
                if(info2.getId().equals("1")){
                    mcostList.get(i).setIsLoan(1);
                    mcostList.get(i).setLoanId("");
                    mcostList.get(i).setLoanNum(new BigDecimal(0));
                }else if(info2.getId().equals("2")){
                    if(isNull(et_jkmoney)||isNull(tv_jkd)){
                        Toast.makeText(mContext, "请完善报销明细", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SpinnerInfo info3=(SpinnerInfo)sp_iscx.getSelectedItem();
                    mcostList.get(i).setLoanState(Integer.parseInt(info3.getId()));
                    mcostList.get(i).setIsLoan(2);
                    mcostList.get(i).setLoanNum(new BigDecimal(et_jkmoney.getText().toString()));
                }

            }
        }


        String costlist = JSON.toJSONString(mcostList);
        Spinner sp_is = (Spinner)findViewById(R.id.sp_is1);
        SpinnerInfo spinnerInfo1=(SpinnerInfo)sp_is.getSelectedItem();
        int result1 = Integer.valueOf(spinnerInfo1.getId());
        travelMaininfo.setIsWithholding(result1);
        travelMaininfo.setExpenseCostFormDetailVoList(mcostList);
        travelMaininfo.setEnclosureNum(String.valueOf(ls_file.size()));
        travelMaininfo.setReimbursementDate(tv_rq.getText().toString());
        travelMaininfo.setState(2);
        if(!isNull(tv_jk)){
            travelMaininfo.setBorrowingMoney(new BigDecimal(tv_jk.getText().toString()));
        }
        travelMaininfo.setMoney( new BigDecimal(tv_hjje.getText().toString()));
        travelMaininfo.setReimbursementType("expenseCost");
        travelMaininfo.setReimbursementTypeName("成本费用");
        travelMaininfo.setFileVoList(ls_file);

        String json = JSON.toJSONString(travelMaininfo);
        bcdata(json);

    }

    /**
     *申请报销单保存数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/21 10:21
     */
    private void bcdata(String json){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);

        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody formBody =  RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),json);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接服务器异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();

                final String str = response.body().string();
                //{"messageType":2,"type":"success","title":"操作信息","message":"提交成功","data":null}
                if(str.indexOf("success")>=0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
                            id = JsonUtil.getMsg(str, "data");
                            layout_tj.setVisibility(View.VISIBLE);
                            layout_bc.setVisibility(View.GONE);

                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });
    }
    /**
     *申请报销单数据请求
     *@author Wangzhiqiang
     *Created on 2017/12/21 10:21
     */
    private void sendExpense(){

        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);

        mOkHttpClient = new OkHttpClient();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("nextAuditorId", nextAuditorId);
        String json1 = JSON.toJSONString(map);
        RequestBody formBody =  FormBody.create(MediaType.parse("application/json;charset=UTF-8"),json1);
        String s = MyApplication.getMsession();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/submitReimbursement")
                .header("cookie", MyApplication.getMsession())
                .addHeader("Content-Type","application/json;charset=UTF-8")
                .post(formBody)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接服务器异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();

                String str = response.body().string();
                //{"messageType":2,"type":"success","title":"操作信息","message":"提交成功","data":null}
                if(str.indexOf("success")>=0){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
                            finish();

                        }
                    });
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });
    }

}
